package com.xyy.ebattery.tcp.app.test;

import com.alibaba.fastjson.JSONObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;



public class NettyTest2 {
    private final static CountDownLatch latch = new CountDownLatch(1);
    public static void main(String[] args) throws InterruptedException {

        String host = "127.0.0.1";
        int port = 10000;

        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
                            pipeline.addLast(new LengthFieldPrepender(4));
                            // 字符串编解码器

                            pipeline.addLast(new StringDecoder(StandardCharsets.UTF_8));
                            pipeline.addLast(new StringEncoder(StandardCharsets.UTF_8));
                        }
                    });

            // 连接到服务器
            ChannelFuture future = bootstrap.connect(host, port).sync();

            // 构造设备注册消息（模拟图片中的格式）
            JSONObject deviceMsg = new JSONObject();
            deviceMsg.put("msgType", 110);          // 消息类型：设备注册
            deviceMsg.put("imsi", "0123456");       // IMSI号
            deviceMsg.put("batteryStatus", "0");    // 电池状态
            deviceMsg.put("hardVersion", "");       // 硬件版本（空）
            deviceMsg.put("softVersion", "");       // 软件版本（空）
            deviceMsg.put("devId", "B11231232");    // 设备ID
            deviceMsg.put("protocolVersion", "V1"); // 协议版本
            deviceMsg.put("devType", 1);            // 设备类型：1-电池
            deviceMsg.put("txnNo", "1234567890123"); // 事务流水号

            // 发送消息
            Channel channel = future.channel();


            // 创建定时任务线程池
            ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
            // 每5秒发送一次（首次立即发送）
            executor.scheduleAtFixedRate(() -> {
                channel.writeAndFlush(deviceMsg.toString());
                System.out.println("Sent: " + deviceMsg.toString());
            }, 0, 5, TimeUnit.SECONDS);

            // 等待响应（原代码保持不变）
            latch.await(5, TimeUnit.SECONDS);


        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
